package com.cn.qgx428.lazydiary.network

import android.content.Context
import android.util.Log
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.cn.qgx428.lazydiary.Utils.ToastHelper
import com.cn.qgx428.lazydiary.Utils.qiniuUtils.Auth
import com.qiniu.android.http.ResponseInfo
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UpProgressHandler
import com.qiniu.android.storage.UploadManager
import com.qiniu.android.storage.UploadOptions
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by qinguanxiong on 2018/3/9.
 */
object Imageloader {
    val AK = "Z6SLvKCMAYRWCii3SYIuzM_fXI4i842FGMfhjrnk"
    val SK = "ROwmPF3Y7gk7LV2q7YrsVWhBFrl9rUHGLSjX0FgJ"
    val bucket = "qimage"
    val uoloadToken = Auth.create(AK, SK).uploadToken(bucket)
    val config = Configuration.Builder().
            connectTimeout(10).
            useHttps(true).build()
    val uplodManager = UploadManager(config)

    /**
     * @path : 文件路径
     * @name : 规定上传至在服务器上的文件名
     */
    fun upload(path: String, fileName: String, listener: (fileName: String)-> Unit){
        uplodManager.put(path, fileName, uoloadToken, object : UpCompletionHandler{
            override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
                if (info!!.isOK){
                    listener(fileName)
                } else{
                    Log.d("Imageloader + 失败：",info!!.error)
                    ToastHelper.toast("上传图片失败：服务器错误")
                }
            }

        }, UploadOptions(
                null,null,false, UpProgressHandler { key, percent ->  },null
        ))

    }


    /**
     * 下载所需
     */
    val loadUrl = "http://p5by8yqg0.bkt.clouddn.com/"

    fun download(context: Context, view: ImageView, fileName: String){
        Log.d("imageLoader", loadUrl+fileName)
        Glide.with(context)
                .load(loadUrl + fileName)
                .into(view)
    }
}